//
//  WithdrawViewController.m
//  联付商圈
//
//  Created by 韩佳睿 on 2017/8/12.
//  Copyright © 2017年 lianfu. All rights reserved.
//

#import "WithdrawViewController.h"
#import "联付商圈-Swift.h"
#import "BankCardModel.h"

@interface WithdrawViewController ()<PassDataDelegate>

@property (weak, nonatomic) IBOutlet UILabel *bankLabel;
@property (weak, nonatomic) IBOutlet UITextField *moneyTextField;
@property (weak, nonatomic) IBOutlet UILabel *bankLastNumberLabel;
@property (weak, nonatomic) IBOutlet UILabel *balanceLabel;
@property (nonatomic, strong)CYPasswordView *passwordView;
@property (nonatomic, strong)NSString *bankNumberStr;
@property (nonatomic, strong)NSString *balanceStr;
@property (nonatomic, strong)BankCardModel *bankCardModel;

@end

@implementation WithdrawViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self refreshDataWithFinishBlock:^(NSString *balance, BankCardModel *model, NSError *error) {
        if (!_bankLastNumberLabel.text) {
            self.bankLabel.text = model.bankType;
            self.bankNumberStr = model.bankNumber;
            self.bankLastNumberLabel.text = [NSString stringWithFormat:@"尾号%@",[model.bankNumber substringFromIndex:model.bankNumber.length-4]];
        }
        self.balanceLabel.text = [NSString stringWithFormat:@"可用余额%@元", balance];
        self.balanceStr = balance;
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self prepareNavBar];
}

- (void)prepareNavBar{
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.title = @"提现";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

- (IBAction)changeBankCardAction:(id)sender {
    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    GuanliViewController * vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"GuanliViewController"];
    [vc setHidesBottomBarWhenPushed:YES];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)withdrawAllMoney:(id)sender {
    self.moneyTextField.text = _balanceStr;
}

- (IBAction)withdrawBtnAction:(id)sender {
    if (!([NSString isNilOrEmpty:_moneyTextField.text]||[NSString isNilOrEmpty:_bankNumberStr]||_moneyTextField.text.integerValue == 0)) {
        SQUserModel *model = [SQUserModel yy_modelWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"]];
        
        __weak WithdrawViewController *weakSelf = self;
        self.passwordView = [[CYPasswordView alloc] init];
        self.passwordView.title = @"请输入支付密码";
        [self.passwordView showInView:self.view.window];
        
        self.passwordView.finish = ^(NSString *password) {
            NSDictionary *param = @{@"name" : model.userName, @"zfmm" : password};
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", nil];
            
            manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
            manager.securityPolicy.allowInvalidCertificates = YES;
            
            [manager POST:[Host stringByAppendingString:@"zfmm?"]  parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                
                [weakSelf.passwordView hideKeyboard];
                [weakSelf.passwordView startLoading];
                
                if (dic[@"success"]) {
                    [weakSelf loadData];
                } else {
                    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                    HUD.labelText = @"支付密码错误";
                    HUD.mode = MBProgressHUDModeText;
                    [HUD hide:YES afterDelay:1.0];
                }
                
                [weakSelf.passwordView stopLoading];
                [weakSelf.passwordView hide];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            }];
        };
    } else {
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        HUD.labelText = @"请选择银行或填写提现金额";
        HUD.mode = MBProgressHUDModeText;
        [HUD hide:YES afterDelay:1.0];
    }

}

- (void)loadData{
    NSString *date = [NSString getNowTimeTimestamp];
    
    SQUserModel *userModel = [SQUserModel yy_modelWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"]];
    
    NSDictionary *param = @{@"BankCardNumber" : _bankNumberStr, @"created_time" : date, @"money" : _moneyTextField.text, @"name" : userModel.userName};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", nil];
    
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    [manager GET:[Host stringByAppendingString:@"tixian?"]  parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if (dic[@"success"]) {
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
            HUD.labelText = @"提现成功";
            HUD.mode = MBProgressHUDModeText;
            [HUD hide:YES afterDelay:1.0];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
}

- (void)refreshDataWithFinishBlock:(void(^)(NSString *balance, BankCardModel *model, NSError *error))finishBolok {
    __block NSString *str;
    __block BankCardModel *bankModel;
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
    SQUserModel *model = [SQUserModel yy_modelWithDictionary:dic];
    NSDictionary *param = @{@"name" : model.userName};
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", nil];
    
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    [manager GET:[Host stringByAppendingString:@"bankxiangqing?"]  parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if (dic[@"yue"]) {
            NSArray *arr = dic[@"yue"];
            NSDictionary *dic1 = arr[0];
            str = dic1[@"money"];
        } else {
            str = @"0.00";
        }
        
        NSArray * arr = dic[@"bank"];
        if (dic[@"bank"]&&arr.count) {
            bankModel = [BankCardModel yy_modelWithDictionary:arr[0]];
        }
        if (finishBolok) {
            finishBolok(str, bankModel, nil);
        }
        
        if (dic[@"error"]) {
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
            HUD.labelText = dic[@"error"][@"message"];
            HUD.mode = MBProgressHUDModeText;
            [HUD hide:YES afterDelay:2.0];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (finishBolok) {
            finishBolok(nil, nil, error);
        }
    }];
}

- (void)setControllerTitleWithText:(NSDictionary *)text  {
    BankCardModel *model = [BankCardModel yy_modelWithDictionary:text];
    _bankLabel.text = model.bankType;
    _bankLastNumberLabel.text = [NSString stringWithFormat:@"尾号%@",[model.bankNumber substringFromIndex:model.bankNumber.length-4]];
    _bankNumberStr = model.bankNumber;
}

@end
